package org.example.controller;

import org.example.entity.Device;
import org.example.repository.DeviceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试控制器
 */
@RestController
@RequestMapping("/test")
public class TestController {
    
    @Autowired
    private DeviceRepository deviceRepository;
    
    @GetMapping("/hello")
    public Map<String, Object> hello() {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "Hello World");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
    
    @GetMapping("/devices")
    public Map<String, Object> testDevices() {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Device> devices = deviceRepository.findAll();
            result.put("success", true);
            result.put("count", devices.size());
            result.put("devices", devices);
            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            e.printStackTrace();
            return result;
        }
    }
    
    @PutMapping("/devices/{id}/properties")
    public Map<String, Object> testUpdateProperties(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("deviceId", id);
            result.put("receivedData", request);
            result.put("message", "测试接口接收数据成功");
            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            e.printStackTrace();
            return result;
        }
    }
    
    @PutMapping("/users/{id}")
    public Map<String, Object> testUpdateUser(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("userId", id);
            result.put("receivedData", request);
            result.put("message", "测试用户更新接口接收数据成功");
            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            e.printStackTrace();
            return result;
        }
    }
}
